package com.controller;

import com.pojo.Dept;
import com.pojo.Message;
import com.pojo.PageBean;
import com.pojo.User;
import com.service.UserService;
import com.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
@CrossOrigin(origins = "http://localhost:8080")
@RestController
@RequestMapping("/user")
@ResponseBody
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    HttpSession session;

    /**
     * 分页查询
     * @param current 当前页
     * @param size 显示的条数
     * @param username 根据用户名查询
     * @return
     */
    @RequestMapping("/findAllUser")
    public PageBean findUserList(Integer current,Integer size,String username) {

        username= username==""|| username==null?"":username;
        return userService.findUserAll(current,size,username);
    }

    @RequestMapping("/login")
    public Message login(String username,String password){
        User user = userService.login(username, password);
        Message message=new Message();
        if(user!=null){
            System.out.println("登录之后");
            System.out.println(user);
            session.setAttribute("user",user);
            String token = TokenUtil.getToken(user.getUsername());
            message.setToken(token);
            message.setMsg("登陆成功！欢迎亲爱的"+user.getUsername());
            message.setUid(user.getId());
            message.setUsername(user.getUsername());
            message.setCode("200");
            message.setStatus("success");
        }else{
            message.setMsg("登陆失败！用户名或密码不正确");
            message.setCode("300");
            message.setStatus("error");
        }
        User user2 = (User) session.getAttribute("user");
        System.out.println("重新获取");
        System.out.println(user2);
       return message;
    }

    @RequestMapping("/addUser")
    public String addUser(@RequestBody User user){
        System.out.println("参数");
        System.out.println(user);
        return userService.addUser(user)>0?"添加成功":"添加失败";
    }
}
